<template>
  <StudentLayout>
    <el-button type="primary" :icon="Plus" @click="addCourseDig()">新增课程</el-button>
    <el-table :data="courseData" style="width: 100%">
      <el-table-column prop="cour_id" label="课程编号" />
      <el-table-column prop="cour_name" label="课程名称" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="addCourseDig(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-popconfirm title="确认删除吗?"
            @confirm="delCourseFun(scope.row)"
          >
            <template #reference>
              <el-button
                size="small"
                type="danger"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </StudentLayout>
  <el-dialog v-model="dialogFormVisible" :title="isEdit?'编辑课程':'新增课程'"
    width="500">
    <el-form :model="form" @submit.native.prevent>
      <el-form-item label="课程名称">
        <el-input v-model="form.cour_name" />
      </el-form-item>
      <el-form-item label="课程编号">
        <el-input v-model="form.cour_id" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button type="primary" @click="addCourseSub()">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import StudentLayout from '@/layouts/StudentLayout.vue'

import { getCourseList, addCourse, editCourse, delCourse } from '@/composables/school'

const courseData = ref()
const courList = async () =>{
  return await getCourseList().then(res => {
    courseData.value = res.data
  })
}

const isEdit = ref(false)
const dialogFormVisible = ref(false)
let form = reactive({
  cour_name: '',
  cour_id: ''
})

const editId = ref()
const addCourseDig = async (index, row) => {
  dialogFormVisible.value = true
  form.cour_name = '' 
  form.cour_id = ''
  isEdit.value = false
  if (row) {
    isEdit.value = true
    form.cour_name = row.cour_name 
    form.cour_id = row.cour_id
    editId.value = row._id
  }
}

const delCourseFun = async (row) => {
  await delCourse({_id: row._id}).then(res => {
    if(res.code === 200) {
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
        courList()
    }
  })
}

const addCourseSub = async () => {
  if (isEdit.value) {
    form._id = editId.value
    await editCourse(form).then(res => {
      if (res.code === 200) {
        dialogFormVisible.value = false
        courList()
      }
    })
  } else {
    await addCourse(form).then(res => {
      if (res.code === 200) {
        dialogFormVisible.value = false
        courList()
      }
    })
  }
}

onMounted(() => {
  courList()
})
</script>
<style scoped>

</style>